package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.impl.DishServiceImpl;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private DishServiceImpl dishServiceImpl;


    // 新增菜品
    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO)
    {
        log.info("新增菜品：{}", dishDTO);
        dishServiceImpl.saveWithFlavor(dishDTO);

        String key ="dish_"+dishDTO.getCategoryId();
        Cleancache(key);

        return Result.success();
    }

    //菜品分页查询
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
       PageResult pageResult = dishServiceImpl.pageQuery(dishPageQueryDTO);
       return Result.success(pageResult);
    }

    // 批量删除菜品
    @DeleteMapping
    public Result deleteBuid(@RequestParam List<Long> ids)
    {
        dishServiceImpl.deleteByIds(ids);
        Cleancache("dish_*");
        return Result.success();
    }
    //启售or 禁售
    @PostMapping("status/{status}")
    public Result updateStatus(@PathVariable String status, Long id)
    {
        dishServiceImpl.updateStatus(status,id);
        Cleancache("dish_*");
        return Result.success();
    }
    //根据id查询菜品
    @GetMapping("/{id}")
    public Result seletById(@PathVariable Long id)
    {
        DishVO dishVO = dishServiceImpl.seletById(id);
        return Result.success(dishVO);
    }
    //修改
    @PutMapping
    public Result updateDish(@RequestBody DishDTO dishDTO)
    {
        log.info("修改菜品 ,{}",dishDTO );
        dishServiceImpl.updateDish(dishDTO);
        Cleancache("dish_*");
        return Result.success();
    }
    //根据分类id查询
    @GetMapping("/list")
    public Result<List<Dish>> selectBycategoryId(Long categoryId)
    {
        List<Dish> dishList = dishServiceImpl.list(categoryId);
        return Result.success(dishList);
    }

    //抽象一个方法来删除redis的缓存数据
    private void Cleancache(String paint)
    {
        Set keys = redisTemplate.keys(paint);
        redisTemplate.delete(keys);
    }

}
